package br.com.advance.automacao.services.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import br.com.advance.automacao.dao.CLPDao;
import br.com.advance.automacao.model.CLP;
import br.com.advance.automacao.services.CLPConnectorFactory;
import br.com.advance.automacao.services.CLPService;
import br.com.advance.automacao.services.dto.EficienciaCLP;
import br.com.advance.automacao.services.exceptions.ValidationException;

@Service
@Transactional(value="transactionManager", rollbackFor=Exception.class)
public class CLPServiceImpl implements CLPService {

	private static final Logger logger = Logger.getLogger(CLPServiceImpl.class);

	@Autowired
	private CLPDao clpDao;

	@Autowired
	private CLPConnectorFactory clpConnectorFactory;

	@Override
	public CLP criar(CLP clp) throws ValidationException {
		validarDados(clp);
		return clpDao.create(clp);
	}

	@Override
	public CLP atualizar(CLP clp) throws ValidationException {
		validarDados(clp);
		return clpDao.update(clp);
	}

	private void validarDados(CLP clp) throws ValidationException {
		CLP clpEncontrado = clpDao.buscarPorNome(clp.getNome());
		if(clpEncontrado != null && (clp.getId() == null || !clpEncontrado.getId().equals(clp.getId()))) {
			throw new ValidationException("Nome já cadastrado.");
		}
		clpEncontrado = clpDao.buscarPorIp(clp.getIp());
		if(clpEncontrado != null && (clp.getId() == null || !clpEncontrado.getId().equals(clp.getId()))) {
			throw new ValidationException("IP já cadastrado.");
		}
	}


	@Override
	public CLP buscarPorId(Long id) {
		return clpDao.findById(id);
	}

	@Override
	public CLP buscarPorIdComErros(Long id) {
		return clpDao.buscarPorIdComErros(id);
	}

	@Override
	public List<CLP> buscarTodosAtivosComErrosPossiveis() {
		return clpDao.buscarTodosAtivosComErrosPossiveis();
	}

	@Override
	public List<CLP> buscarTodosAtivos() {
		return clpDao.buscarTodosAtivos();
	}

	@Override
	public List<EficienciaCLP> buscarEficienciaCLPs() {
		logger.info("Iniciando busca de eficiencia dos clps");
		List<CLP> listaClps = clpDao.buscarTodosAtivos();
		if(listaClps.isEmpty()) {
			logger.error("Nao foi encontrado nenhum CLP.");
			return null;
		}
		List<EficienciaCLP> lista = new ArrayList<EficienciaCLP>();
		for(CLP clp : listaClps) {
			logger.info("Buscando eficiencia do CLP ID: "+ clp.getId() + " IP: " + clp.getIp() + " Nome: " + clp.getNome());
			EficienciaCLP eficiencia = clpConnectorFactory.getCLPConector(clp.getFabricante()).obterEficienciaCLP(clp);
			if(eficiencia == null) {
				logger.error("Erro ao buscar dados de eficiencia do CLP ID: "+ clp.getId() + " IP: " + clp.getIp() + " Nome: " + clp.getNome());
			} else {
				lista.add(eficiencia);
			}
		}
		return lista;
	}

	@Override
	public List<CLP> buscarTodos() {
		return clpDao.findAll();
	}
}
